package org.jupiter.blog.authentic.handler;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jupiter.blog.authentic.constant.AuthenticConstant;
import org.jupiter.blog.authentic.service.TokenService;
import org.jupiter.blog.redis.component.SpringRedisRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Collections;

@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

	@Autowired
	private TokenService tokenService;

	@Autowired
	private SpringRedisRepository redisRepository;

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
				FilterChain filterChain) throws ServletException, IOException {

		String authorization = request.getHeader("Authorization");
		if (authorization != null && authorization.startsWith("Bearer ")) {
			String token = authorization.substring(7);
			boolean valid = tokenService.validateToken(token);
			String username = redisRepository.get(AuthenticConstant.AUTH_TOKEN_PREFIX + token, String.class);
			if (valid && username != null) {
				String forceFlag = redisRepository.get(AuthenticConstant.AUTH_SESSION_PREFIX + username, String.class);
				if (!"FORCE_LOGOUT".equals(forceFlag)) {
					UsernamePasswordAuthenticationToken authToken =
							new UsernamePasswordAuthenticationToken(username, null, Collections.emptyList());
					SecurityContextHolder.getContext().setAuthentication(authToken);
				}
			}
		}

		filterChain.doFilter(request, response);
	}
}


